#include "WCom.h"
#include <stdio.h>
#include <string.h>


using namespace std;

WCom::WCom(){
	cout << "Configuring server ..." << endl;
	ServerSocket = socket(AF_INET, SOCK_STREAM, 0);
	memset(&serv_addr, '0', sizeof(serv_addr));

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(5000); 

	if(bind(ServerSocket, (struct sockaddr*)&serv_addr, sizeof(serv_addr))==-1)
		cout << "Problem starting server." << endl;

	if(listen(ServerSocket, 100)==-1)
		cout << "Can't set the queue size." << endl;
	
}

void startListenning(int SrvSock){
	struct sockaddr_in client_addr;
	int ClientSocket;
	char buffer[32]="";
	
	memset(&client_addr, '0', sizeof(client_addr));
	
	cout << "Waiting for new connection ..." << endl;
	socklen_t ClientAddrSize = sizeof(client_addr);
	ClientSocket=accept(SrvSock, (struct sockaddr*)&client_addr, &ClientAddrSize);
	cout << "Connection accepted." << endl;
	
	
	while(recv(ClientSocket,buffer,32,0) == -1){
	}
	
	cout << " -> " << buffer << endl;
	
	
	close(ClientSocket);
}

void WCom::startServer(){
	tListenning = new boost::thread(&startListenning, ServerSocket);
	while(getchar()!='n');
}

void WCom::stopServer(){
	cout << "Stoping server ..." << endl;
	close(ServerSocket);
}

